package top.bugger168.auth.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;
import top.bugger168.base.exception.CourseOnlineException;
import top.bugger168.ucenter.feignclient.CheckCodeClient;
import top.bugger168.ucenter.mapper.XcUserMapper;
import top.bugger168.ucenter.mapper.XcUserRoleMapper;
import top.bugger168.ucenter.model.dto.FindPasswordDto;
import top.bugger168.ucenter.model.dto.RegisterDto;
import top.bugger168.ucenter.model.po.XcUser;
import top.bugger168.ucenter.model.po.XcUserRole;

import javax.annotation.Resource;
import java.time.LocalDateTime;

/**
 * 测试controller
 *
 * @author wanghaidong
 * @date 2023/08/28
 */
@Slf4j
@RestController
public class LoginController {

    @Resource
    XcUserMapper userMapper;
    @Resource
    XcUserRoleMapper userRoleMapper;
    @Resource
    CheckCodeClient checkCodeClient;


    @RequestMapping("/login-success")
    public String loginSuccess() {
        return "登录成功";
    }


    @RequestMapping("/user/{id}")
    public XcUser getUser(@PathVariable("id") String id) {
        return userMapper.selectById(id);
    }


    @PostMapping("/findpassword")
    public void findpassword(@RequestBody FindPasswordDto findPasswordDto){
        if(!verifyUser(findPasswordDto)){
            CourseOnlineException.cast("验证码或密码校验失败");
        }
        // 查表更新数据
        LambdaQueryWrapper<XcUser> queryWrapper = new LambdaQueryWrapper<>();
        if(StringUtils.isNotBlank(findPasswordDto.getCellphone())){
            // 有手机号优先校验手机号
            queryWrapper.eq(XcUser::getCellphone, findPasswordDto.getCellphone());
        }else if(StringUtils.isNotBlank(findPasswordDto.getEmail())){
            queryWrapper.eq(XcUser::getEmail, findPasswordDto.getEmail());
        }else {
            CourseOnlineException.cast("手机号和邮箱为空");
        }
        // 更新数据库内容
        XcUser user = userMapper.selectOne(queryWrapper);
        user.setPassword(new BCryptPasswordEncoder().encode(findPasswordDto.getPassword()));
        userMapper.updateById(user);
    }

    @PostMapping("/register")
    public void register(@RequestBody RegisterDto registerDto){
        if(!verifyUser(registerDto)){
            CourseOnlineException.cast("验证码或密码校验失败");
        }
        // 校验用户是否已经存在,存在则抛异常
        LambdaQueryWrapper<XcUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(XcUser::getName,registerDto.getUsername());
        XcUser user = userMapper.selectOne(queryWrapper);
        if(user!=null){
            CourseOnlineException.cast("该用户已存在");
        }else{
            // 写用户表
            user = new XcUser();
            BeanUtils.copyProperties(registerDto,user);
            user.setName(registerDto.getNickname());
            user.setUtype("101001");
            user.setPassword(new BCryptPasswordEncoder().encode(registerDto.getPassword()));
            user.setCreateTime(LocalDateTime.now());
            user.setStatus("1");
            userMapper.insert(user);

            // 写用户角色关系表
            XcUserRole userRole = new XcUserRole();
            userRole.setRoleId("17");
            userRole.setUserId(user.getId());
            userRole.setCreateTime(LocalDateTime.now());
            userRoleMapper.insert(userRole);
        }

    }

    @SuppressWarnings("BooleanMethodIsAlwaysInverted")
    private boolean verifyUser(FindPasswordDto findPasswordDto){
        // 校验验证码
        Boolean back = checkCodeClient.verify(findPasswordDto.getCheckcodekey(), findPasswordDto.getCheckcode());
        if(!back) {
            throw new CourseOnlineException("验证码错误");
        }
        // 校验两次密码一致
        if(StringUtils.isBlank(findPasswordDto.getPassword())){
            throw new CourseOnlineException("密码为空");
        }
        if(!findPasswordDto.getPassword().equals(findPasswordDto.getConfirmpwd())){
            throw new CourseOnlineException("密码不一致");
        }
        return true;
    }

}
